package com.aabte.auth.account.resource.api;

import com.aabte.auth.account.domain.exception.AccountAccountOrPasswordException;
import com.aabte.auth.account.domain.exception.AccountExistException;
import com.aabte.auth.account.domain.model.AccountId;
import com.aabte.auth.account.resource.api.account.AccountApi;
import com.aabte.auth.account.resource.api.account.AccountDTO;
import com.aabte.auth.account.resource.api.account.ChangePasswordCommand;
import com.aabte.auth.account.resource.api.account.RegistrationCommand;
import com.aabte.auth.account.resource.facade.AccountServiceFacade;
import com.aabte.commons.bean.BaseResponse;
import com.aabte.commons.errorcode.ResponseFactory;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

@Validated
@RestController
public class AccountController implements AccountApi {

    @Resource
    private AccountServiceFacade accountServiceFacade;

    @Override
    public BaseResponse<String> register(RegistrationCommand command) {
        AccountId accountId;
        try {
            accountId = accountServiceFacade.register(
                    command.getAccountName(), command.getAccountPassword());
        } catch (AccountExistException e) {
            throw AccountCode.ACCOUNT_EXIST.newException(e);
        }
        return ResponseFactory.success(accountId.getId());
    }

    @Override
    public BaseResponse<Boolean> updatePassword(@Valid ChangePasswordCommand command) {
        try {
            accountServiceFacade.updatePassword(
                    command.getAccountName(),
                    command.getAccountOldPassword(),
                    command.getAccountNewPassword());
        } catch (AccountAccountOrPasswordException e) {
            throw AccountCode.ACCOUNT_NOT_EXIST_OR_PASSWORD_INCORRECT_EXIST.newException(e);
        }
        return ResponseFactory.success(true);
    }

    @Override
    public BaseResponse<Page<AccountDTO>> accounts(Integer pageNumber, Integer pageSize) {
        return ResponseFactory.success(accountServiceFacade.accounts(pageNumber, pageSize));
    }

}
